import { Form, Table, Input, Button, Pagination, type InputValue, message, PrimaryTable, Avatar, Badge } from 'tdesign-react';
import React, { useState, useEffect, ChangeEvent } from 'react';
import EmployeeModal from 'components/EmployeeModal';
import ConfirmModal from 'components/ConfirmModal';
import { getEmployeeList, addEmployee, updateEmployee, deleteEmployee } from 'services/employee';
import type { User, UserListRequest, UserListResponse } from 'services/employee';
// eslint-disable-next-line import/no-extraneous-dependencies
// import { Modal } from 'react-bootstrap';
import axios from 'axios';
import 'tdesign-react/es/style/index.css';

const EmployeeManage: React.FC = () => {
  const [employeeList, setEmployeeList] = useState<User[]>([]);
  const [pagination, setPagination] = useState<{
    page: number;
    pageSize: number;
    total: number;
  }>({ page: 1, pageSize: 20, total: 0 });
  const [searchKey, setSearchKey] = useState('');
  const [isModalVisible, setIsModalVisible] = useState(false); // 新增弹窗
  const [isEditing, setIsEditing] = useState(false); // 编辑弹窗
  // const [editingEmployee, setEditingEmployee] = useState<User>(); // 编辑数据
  const companyId = '998a5805-ff3d-477d-a598-8348db542ccf';
  const [isDeleting, setIsDeleting] = useState(false); // 删除确认
  const [deletingId, setDeletingId] = useState(''); // 待删除 ID
  const [editingEmployee, setEditingEmployee] = useState<User | undefined>({});

  const [initialData, setInitialData] = useState<Record<string, any>>({});

  // 获取员工列表
  const fetchEmployeeList = async () => {
    // eslint-disable-next-line no-restricted-globals
    const page = isNaN(pagination.page) ? 1 : Math.max(1, pagination.page);
    const size = Math.min(100, Math.max(1, pagination.pageSize));
    const params: UserListRequest = {
      company_id: companyId,
      page,
      size,
      search: searchKey || null,
    };

    // console.log('请求参数:', params);

    try {
      const res = await getEmployeeList(params);
      console.log('后端返回数据:', res); // 打印完整响应

      // 修正后应根据实际响应结构调整
      setEmployeeList(res.data.items || []);
      setPagination({ ...pagination, total: res.data.total || 0 });


      // // 关键修复：根据实际数据结构调整
      // const dataArray = Array.isArray(res.data) ? res.data : [];

      // setEmployeeList(dataArray);
      // setPagination({
      //   ...pagination,
      //   total: res.total || dataArray.length // 添加后备值
      // });
    } catch (error) {
      console.error('请求失败:', error);
      setEmployeeList([]);
      setPagination({ ...pagination, total: 0 });
    }
  };

  useEffect(() => {
    console.log('分页状态变更:', pagination);
    fetchEmployeeList();
  }, [pagination.page, pagination.pageSize, searchKey, companyId]);

  // useEffect(() => {
  //   fetchEmployeeList();
  // }, [pagination.page, pagination.pageSize, searchKey]);



  // 搜索
  const handleSearch = () => {
    setPagination((prev) => ({
      ...prev,
      page: 1,  // 明确使用数字 1
      pageSize: prev.pageSize
    }));
    // 延迟调用确保状态更新
    setTimeout(fetchEmployeeList, 0);
    // setPagination({ ...pagination, page: 1 });
    // fetchEmployeeList();
  };

  // 新增员工
  const handleAdd = () => {
    setIsModalVisible(true); // 显示弹窗
    setIsEditing(false); // 标记为“新增”模式
    setInitialData({}); // 初始化数据为空（新增场景）
  };

  // 编辑员工
  const handleEdit = (employee: User) => {
    setIsEditing(true);
    setEditingEmployee({ ...employee });
  };
  // 弹窗取消回调：关闭弹窗
  const handleCancel = () => {
    setIsModalVisible(false);
  };

  // 保存员工（新增/编辑）
  const handleSave = async (data: User) => {
    try {
      if (isEditing && editingEmployee) {
        // 编辑：调用 update 接口
        await updateEmployee(editingEmployee.nick_name, data);
      } else {
        // 新增：调用 add 接口
        await addEmployee({ ...data, company_id: companyId });
      }
      // 操作成功后刷新列表
      await fetchEmployeeList();
      // 关闭弹窗
      setIsModalVisible(false); // 关闭弹窗
      setIsEditing(false);
      setEditingEmployee(undefined);
    } catch (error) {
      // 错误已在接口拦截器处理，可自定义额外提示
      message.error('保存失败，请重试');
    }
    // if (isEditing && editingEmployee) {
    //   await updateEmployee(editingEmployee.id, data);
    // } else {
    //   await addEmployee(data);
    // }
    // fetchEmployeeList();
    // setIsAdding(false);
    // setIsEditing(false);
  };

  // 删除确认
  const handleDelete = (nick_name) => {
    setIsDeleting(true);
    setDeletingId(nick_name);
  };

  // 确认删除
  const confirmDelete = async () => {
    try {
      await deleteEmployee(deletingId);
      await fetchEmployeeList();
      setIsDeleting(false);
      setDeletingId('');
    } catch (error) {
      message.error('删除失败，请重试');
    }

    // await deleteEmployee(deletingId);
    // fetchEmployeeList();
    // setIsDeleting(false);
  };

  const handleChange = (value: InputValue) => {
    setSearchKey(value as string);
  };

  // 表格列配置
  const columns = [
    {
      title: '序号',
      colKey: 'index',
      render: (_: any, __: any, index: number) => index + 1,
    },
    {
      title: '姓名',
      dataIndex: 'nick_name',
      colKey: 'nick_name',
    },
    { title: '工号', dataIndex: 'job_number', colKey: 'job_number' },
    { title: '岗位', dataIndex: 'position', colKey: 'position' },
    { title: '联系电话', dataIndex: 'phone', colKey: 'phone' },
    { title: '权限', dataIndex: 'permissions', colKey: 'permissions', },
    {
      title: '帐号状态',
      dataIndex: 'registered',
      colKey: 'registered',
    },
    {
      title: '最后操作时间',
      dataIndex: 'updated_at',
      colKey: 'updated_at',
    },
    
    {
      title: '操作',
      colKey: 'operation',
      width: 100,
      fixed: 'right',
      ellipsis: ({ row }) => row.operation,
      cell: ({ row }) => (
        <>
          <a onClick={() => handleEdit(employee)}>修改权限{row.operation}</a>
       
          <a onClick={() => handleDelete(employee.nick_name)}>删除{row.operation}</a>
        </>
      )
      // render: (employee: User) => (
      //   <div style={{ display: 'flex', gap: '8px' }}>
      //     <a onClick={() => handleEdit(employee)}>修改权限</a>
      //     <a onClick={() => handleDelete(employee.nick_name)}>删除</a>
      //   </div>
      // ),
    
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      {/* 搜索 + 新增 */}
      <div style={{ display: 'flex', gap: '8px', marginBottom: '16px' }}>
        <Input
          placeholder='请输入姓名/工号搜索'
          value={searchKey}
          // onChange={(e) => setSearchKey(e.target.value)} 
          onChange={handleChange}
          onEnter={handleSearch}
        />
        <Button theme='primary' onClick={handleAdd}>
          + 添加员工
        </Button>

      </div>

      {/* 员工列表 */}
      <Table<User>
        data={employeeList || []}
        columns={columns}
        pagination={undefined}// 关闭内置分页，用自定义
        rowKey='nick_name'
        stickyHeader
        style={{ width: '100%' }}
      />
      <Pagination
        current={pagination.page}
        pageSize={pagination.pageSize}
        total={pagination.total}
        onChange={(pageInfo) =>
          setPagination({
            ...pagination,
            page: pageInfo.page,
            pageSize: pageInfo.pageSize
          })
        }
        // onChange={(pageInfo) => setPagination({ ...pagination, page: pageInfo.page, pageSize: pageInfo.pageSize })}
        style={{ marginTop: '16px' }}
      />

      {/* 新增/编辑弹窗 */}
      <EmployeeModal
        visible={isModalVisible || isEditing}
        isEdit={isEditing}
        initialData={editingEmployee}
        // onSave={handleSave}
        onSave={() => {
          if (!editingEmployee) return; // 新增场景需确保表单数据完整
          handleSave(editingEmployee);
        }}
        onCancel={() => {
          setIsModalVisible(false);
          setIsEditing(false);
          setEditingEmployee(undefined);
        }}
      >
        {/* 弹窗内容：可使用 Form 组件对齐后端字段校验，此处简化演示 */}
        <Form>
          <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
            <Input
              label='姓名'
              value={editingEmployee?.nick_name || ''}
              onChange={(e) =>
                setEditingEmployee({
                  ...editingEmployee,
                  nick_name: e.target.value,
                })
              }
            />
            <Input
              label='工号'
              value={editingEmployee?.job_number || ''}
              onChange={(e) =>
                setEditingEmployee({
                  ...editingEmployee,
                  job_number: e.target.value
                })
              }
            />
            <Input
              label='联系电话'
              value={editingEmployee?.phone || ''}
              onChange={(e) => {
                const phone = e.target.value.trim();
                // 简单校验：长度 11 位
                if (phone?.length === 11) {
                  setEditingEmployee({ ...editingEmployee, phone });
                } else {
                  message.error('手机号必须为 11 位');
                }
              }}
            />
            <Input
              label='岗位'
              value={editingEmployee?.position || ''}
              onChange={(e) =>
                setEditingEmployee({
                  ...editingEmployee,
                  position: e.target.value
                })}
            />
            <Input
              label='权限列表'
              value={editingEmployee?.permissions || ''}
              onChange={(e) =>
                setEditingEmployee({
                  ...editingEmployee,
                  permissions: e.target.value
                })}
            />
            <Input
              label='账号状态'
              value={editingEmployee?.registered || ''}
              onChange={(e) =>
                setEditingEmployee({
                  ...editingEmployee,
                  registered: e.target.value
                })}
            />
          </div>
        </Form>
      </EmployeeModal>
      {/* 删除确认弹窗 */}
      <ConfirmModal
        visible={isDeleting}
        title='确认删除'
        content='删除后员工信息将无法恢复，是否继续？'
        onConfirm={confirmDelete}
        onCancel={() => {
          setIsDeleting(false);
          setDeletingId('nick_name');
        }}
      />
    </div>
  );
};

export default EmployeeManage;
// export default memo(() => <div>员工列表-待开发</div>);
